"use strict";
const path = require("path");
const Service = require("egg").Service;
var pdfMakePrinter = require("pdfmake/src/printer.js");
class PdfService extends Service {
  create(payload = {}) {
    return new Promise((resolve, reject) => {
      try {
        var pdfDoc = Object.assign(payload, {
          defaultStyle: {
            font: "msyh"
          }
        });
        var fontDescriptors = {
          msyh: {
            normal: path.join(__dirname, "../fonts/msyh.ttf"),
            bold: path.join(__dirname, "../fonts/msyh.ttf"),
            italics: path.join(__dirname, "../fonts/msyh.ttf"),
            bolditalics: path.join(__dirname, "../fonts/msyh.ttf")
          }
        };

        var printer = new pdfMakePrinter(fontDescriptors);
        var doc = printer.createPdfKitDocument(pdfDoc);

        var chunks = [];
        var result;

        doc.on("data", function(chunk) {
          chunks.push(chunk);
        });
        doc.on("end", function() {
          result = Buffer.concat(chunks);
          resolve(result);
        });
        doc.end();
      } catch (ex) {
        reject(ex.message);
      }
    });
  }
}

module.exports = PdfService;
